package com.yxd.bdmapdemo;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.yxd.bdmapdemo.base.BaseActivity;
import com.yxd.bdmapdemo.utils.L;
import com.yxd.bdmapdemo.utils.PermissionUtils;

import java.util.ArrayList;
import java.util.List;


public class HelloBdMapActivity extends BaseActivity {

    private TextureMapView mMapView;
    private BaiduMap mBaiduMap;
    private Spinner spin;
    private Spinner spin1;
    BdLocManager manager;
    private ImageView img_location;
    private boolean isChecked;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        isChecked = true;
        getBdKeyConfig();
        mMapView = (TextureMapView) findViewById(R.id.bmapView);
        userSpineer();
        initListener();
        //获取地图控制器
        mBaiduMap = mMapView.getMap();

        // mMapView.showScaleControl(false);//隐藏比例尺按钮，默认显示
        // mMapView.showZoomControls(false);//隐藏缩放按钮，默认显示
        mMapView.removeViewAt(1);//移除百度图标

        float maxZoomLevel = mBaiduMap.getMaxZoomLevel();//获取地图最大缩放级别
        float minZoomLevel = mBaiduMap.getMinZoomLevel();//获取地图最小缩放级别
        L.d("maxZoomLevel = " + maxZoomLevel + " minZoomLevel =" + minZoomLevel);

        //设置地图缩放级别
        MapStatusUpdateFactory.zoomTo(15);
        //设置地图中心点
        LatLng latLng = new LatLng(40.050513, 116.30361);//维度经度
        //地图各种状态
        MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLng(latLng);
        mBaiduMap.setMapStatus(mapStatusUpdate);

        //针对已经添加在地图上的标注Marker,设置marker拖拽的监听
        mBaiduMap.setOnMarkerDragListener(new BaiduMap.OnMarkerDragListener() {
            public void onMarkerDrag(Marker marker) {
                //拖拽中
                L.d("拖拽中");
            }

            public void onMarkerDragEnd(Marker marker) {
                //拖拽结束
                LatLng position = marker.getPosition();
                L.d("拖拽结束" + position.latitude);

            }

            public void onMarkerDragStart(Marker marker) {
                //开始拖拽
                L.d("开始拖拽");
            }
        });
        L.d("HelloBdMapActivity#onCreate");

        manager = new BdLocManager(this, mBaiduMap);
        manager.registerLocLisener();
        manager.start();


    }


    private void initListener() {
        findViewById(R.id.img_location).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        findViewById(R.id.btn_per).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(HelloBdMapActivity.this, SetPermissionActivity.class));
            }
        });
    }

    //获取百度地图key
    private void getBdKeyConfig() {
        try {
            //用这种方式拿配置信息
            ApplicationInfo info = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
            Bundle bundle = info.metaData;
            String bdKey = bundle.getString("com.baidu.lbsapi.API_KEY");
            //这种方式拿不到，bundle为null
            // Bundle bundle = getApplication().getApplicationInfo().metaData;
            // String bakey1 = bundle.getString("com.baidu.lbsapi.API_KEY");

            L.d("yxd---" + bdKey);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    Overlay markerOverlay;
    Overlay textOverlay;

    //移除标注
    private void removeMarker() {
        // bdMap.clear();//移除地图上所有标记
        if (markerOverlay != null) {
            markerOverlay.remove();
        }
    }

    /**
     * 根据经纬度在地图上添加标注
     * 维度latitude：从赤道到北极是N0 - N90 我国大概在N34 北纬34
     * 经度lontitude：本初子午线（英国伦敦格林威治一条线）往西- 西经w0-w180 往东-东经s0-s180 我国大概在东经117
     */
    private void addMarker(double latitude, double lontitude) {
        //定义坐标点
        LatLng point = new LatLng(latitude, lontitude);//纬度经度
        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.icon_openmap_focuse_mark);
        BitmapDescriptor bitmap2 = BitmapDescriptorFactory.fromResource(R.mipmap.icon_openmap_mark);
        ArrayList<BitmapDescriptor> list = new ArrayList<>();
        list.add(bitmap);
        list.add(bitmap2);
        //构建MarkerOption，用于在地图上添加Marker
        /*OverlayOptions*/
        MarkerOptions option = new MarkerOptions()
                .position(point)
                .icons(list)//添加多个图标，会不停切换
                .zIndex(15)  //设置marker所在层级
                .period(100)// 通过marker的icons设置一组图片，再通过period设置多少帧刷新一次图片资源
                .alpha(0.5f)//给Marker设置透明度
                .animateType(MarkerOptions.MarkerAnimateType.grow) // 生长动画
                .draggable(true);  //设置手势拖拽
        //.icon(bitmap);//添加一个图标
        // if (animationBox.isChecked()) {
        //  option .animateType(MarkerOptions.MarkerAnimateType.drop) ;// 生长动画
        // }
        markerOverlay = mBaiduMap.addOverlay(option);
        // marker = (Marker) (mBaiduMap.addOverlay(options));

    }

    //百度城市热力图
    private void setRelitu(int type) {
        if (type == 1) {
            //关闭百度城市热力图
            mBaiduMap.setBaiduHeatMapEnabled(false);
        } else if (type == 2) {
            //开启百度城市热力图
            mBaiduMap.setBaiduHeatMapEnabled(true);
        }
    }

    //交通图
    private void setJiaotong(int type) {
        L.d("type = " + type);
        if (type == 1) {
            //关闭交通图
            mBaiduMap.setTrafficEnabled(false);
        } else if (type == 2) {
            //开启交通图
            mBaiduMap.setTrafficEnabled(true);
        }
    }

    //设置卫星地图、普通地图
    private void setTuCeng(int type) {
        if (type == 1) {
            //卫星地图
            mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
        } else if (type == 2) {
            //普通地图
            mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        }
    }

    //移除文字覆盖物
    private void removeText() {
        if (textOverlay != null) {
            textOverlay.remove();
        }
    }

    //添加文字覆盖物
    private void addText(double latitude, double lontitude) {
        //定义文字所显示的坐标点
        LatLng llText = new LatLng(latitude + 0.0005, lontitude + 0.0005);
        //构建文字Option对象，用于在地图上添加文字
        OverlayOptions textOption = new TextOptions()
                .bgColor(0x00FFFF00)
                .fontSize(30)
                .fontColor(0x50FF00FF)
                .text("小东地图")
                .rotate(-30)
                .position(llText);
        //在地图上添加该文字对象并显示
        //overlay是一个添加的标记

        textOverlay = mBaiduMap.addOverlay(textOption);
    }


    private void userSpineer() {
        spin = (Spinner) findViewById(R.id.spin);
        spin1 = (Spinner) findViewById(R.id.spin1);
        final List<String> list = new ArrayList<>();
        list.add("功能");
        list.add("交通图-开");
        list.add("百度城市热力图-开");
        list.add("地图标注-开");
        list.add("普通地图");
        list.add("添加文字覆盖物");

        final List<String> list1 = new ArrayList<>();
        list1.add("功能");
        list1.add("交通图-关");
        list1.add("百度城市热力图-关");
        list1.add("地图标注-关");
        list1.add("卫星地图");
        list1.add("移除文字覆盖物");
      /*  list.add("添加地图标注");
        list.add("移除地图标注");


        list.add("显示我的位置");
        list.add("隐藏我的位置");*/
        spin.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list));
        spin1.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list1));
        spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            //条目选中 是回调
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 1:
                        setJiaotong(2);
                        break;
                    case 2:
                        setRelitu(2);
                        break;
                    case 3:
                        //添加地图标注
                        addMarker(39.963175, 116.400244);
                        break;
                    case 4:
                        setTuCeng(2);
                        break;
                    case 5:
                        addText(39.963175, 116.400244);

                        break;
                    case 6:

                        break;
                    case 7:
                        // addText(39.963175, 116.400244);
                        break;
                    case 8:
                        // removeText();
                        break;
                    case 9:
                        // showMyLocation();
                        break;
                    case 10:
                        // hideMyLocation();
                        break;

                }
            }

            //打开了条目，但是还没选
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spin1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            //条目选中 是回调
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 1:
                        setJiaotong(1);
                        break;
                    case 2:
                        setRelitu(1);
                        break;
                    case 3:
                        removeMarker();
                        break;
                    case 4:
                        setTuCeng(1);
                        break;
                    case 5:
                        removeText();

                        break;
                    case 6:

                        break;
                    case 7:
                        // addText(39.963175, 116.400244);
                        break;
                    case 8:
                        // removeText();
                        break;
                    case 9:
                        // showMyLocation();
                        break;
                    case 10:
                        // hideMyLocation();
                        break;

                }
            }

            //打开了条目，但是还没选
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
        manager.stop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
        L.d("HelloBdMapActivity#onResume");
        if (isChecked) {
            PermissionUtils.checkPer(HelloBdMapActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION, "请求位置权限",
                    new PermissionUtils.VersionLowMListener() {
                        @Override
                        public void versionLowMAction() {
                            Toast.makeText(HelloBdMapActivity.this, "请求位置权限成功", Toast.LENGTH_SHORT).show();
                        }
                    });
            isChecked=false;
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }
}
